<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="优惠类型" prop="groupId">
        <el-select v-model="queryParams.couponType" size="small">
          <el-option label="全部"
                     key="0"
                     value="0">
          </el-option>
          <el-option
            v-for="dict in couponType"
            :key=dict.dictValue
            :label="dict.dictLabel"
            :value=dict.dictValue
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="openAddDialog"
          v-hasPermi="['shop:coupon:add']"
        >添加
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList">
      <el-table-column label="名称" align="center" prop="couponName"/>
      <el-table-column label="类型" :formatter="couponTypeFormat" align="center" prop="couponType"/>
      <el-table-column label="是否可用" align="center" prop="isShow">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isShow"
            :active-value='1'
            :inactive-value='0'
            @change="handleIsShowChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="无限次使用" align="center" key="couponStatus">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.couponStatus"
            :active-value='2'
            :inactive-value='1'
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="剩余张数" align="center" prop="stock"/>
      <el-table-column label="满多少减" align="center" prop="couponFull"/>
      <el-table-column label="减多少" align="center" prop="reduce"/>
      <el-table-column label="开始时间" :formatter="dateFormat" align="center" prop="startTime"/>
      <el-table-column label="结束时间" :formatter="dateFormat" align="center" prop="endTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="openUpdateDialog(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :hide-on-single-page="false"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @size-change="sizeChange"
      @current-change="pageChange"
    />
    <el-dialog
      :visible.sync="open"
      :title="title"
      width="50%" append-to-body
    >
      <el-form :rules="rules" :model="formData" label-width="150px" ref="form">
        <el-row>
          <el-col :span="20">
            <el-form-item label="优惠券名称" prop="couponName">
              <el-input v-model="formData.couponName" placeholder="请输入优惠券名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="优惠券类型" prop="couponType">
              <el-select v-model="formData.couponType" placeholder="优惠券类型" size="small">
                <el-option
                  v-for="dict in couponType"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="优惠券数量" prop="stock">
              <el-input v-model.number="formData.stock" placeholder="请输入优惠券数量"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="满多少" prop="couponFull">
              <el-input v-model.number="formData.couponFull" placeholder="填0则为无门槛"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="减多少" prop="reduce">
              <el-input v-model.number="formData.reduce" placeholder="减多少"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="领取之后几天可用" prop="couponDay">
              <el-input v-model.number="formData.couponDay" placeholder="填0则为范围时间可用的优惠券"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="可用时间" prop="startTime">
              <el-date-picker
                v-model="formData.startTime"
                type="datetimerange"
                :default-time="['00:00:00', '00:00:00']">
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="open = false">取 消</el-button>
        <el-button type="primary" @click="handleAddOrUpdate">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import * as couponApi from "@/api/shop/coupon";
import moment from "moment";

export default {
  name: "ShopCoupon",
  components: {},
  data() {
    let checkStock = (rule, value, callback) => {
      if (value != 0 && !value) {
        return callback(new Error('数量不能为空'));
      }
      if (!Number.isInteger(value)) {
        callback(new Error('请输入数字值'));
      } else {
        if (value <= 0) {
          callback(new Error('数量必须大于0'));
        } else {
          callback();
        }
      }
    };
    let checkReduce = (rule, value, callback) => {
      if (value != 0 && !value) {
        return callback(new Error('满减额度不能为空'));
      }
      if (!Number.isInteger(value)) {
        callback(new Error('请输入数字值'));
      } else {
        if (value <= 0) {
          callback(new Error('满减额度必须大于0'));
        } else {
          callback();
        }
      }
    };
    let checkCouponFull = (rule, value, callback) => {
      if (value != 0 && !value) {
        return callback(new Error('满减门槛不能为空'));
      }
      if (!Number.isInteger(value)) {
        callback(new Error('请输入数字值'));
      } else {
        if (value < 0) {
          callback(new Error('满减门槛必须大于等于0'));
        } else {
          callback();
        }
      }
    };
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        couponType: '0'
      },
      showSearch: true,
      total: 0,
      //广告列表数据
      couponList: [],
      //优惠券类型
      couponType: [],
      // 遮罩层
      loading: false,
      //是否打开遮罩层
      open: false,
      //弹出框的标题
      title: '',
      //提交或修改时的表单内容
      formData: {
        couponType: '1'
      },
      //表单校验规则
      rules: {
        couponName: [{required: true, message: "优惠券名称不能为空", trigger: "blur"}],
        stock: [{required: true, validator: checkStock, trigger: "blur"}],
        startTime: [{required: true, message: "可用时间不能为空", trigger: "blur"}],
        reduce: [{required: true, validator: checkReduce, trigger: "blur"}],
        couponFull: [{required: true, validator: checkCouponFull, trigger: "blur"}]
      }
    }
  }
  ,
  computed: {},
  created() {
    this.getList();
    this.getDicts("coupon_type").then(response => {
      this.couponType = response.data;
    });
  }
  ,
  methods: {
    dateFormat(row, column, cellValue, index) {
      return moment(cellValue).format('YYYY-MM-DD HH:MM');
    },
    getList() {
      couponApi.getAllCoupon(this.queryParams).then((res) => {
        this.total = res.total;
        this.couponList = res.rows
      });
    }
    ,
    couponTypeFormat(row) {
      return this.selectDictLabel(this.couponType, row.couponType);
    }
    ,
    handleIsShowChange(row) {
      let text = row.isShow === 1 ? "启用" : "停用";
      this.$confirm('确认要' + text + '本张优惠券吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return couponApi.updateOrSave(row);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function () {
        row.isShow = row.isShow === 0 ? 1 : 0;
      });
    }
    ,
    handleStatusChange(row) {
      let text = row.couponStatus === 1 ? "使用一次" : "使用无限次";
      this.$confirm('确认要将本张优惠券改为' + text + '吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return couponApi.updateOrSave(row);
      }).then(() => {
        this.msgSuccess('更改成功');
      }).catch(function () {
        row.couponStatus = row.couponStatus === 1 ? 2 : 1;
      });
    },
    sizeChange(val) {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = val
      this.getList()
    }
    ,
    pageChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    }
    ,
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    }
    ,
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    }
    ,
    handleDelete(row) {
      this.$confirm('确认要删除本张优惠券么?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return couponApi.deleteObj(row.id);
      }).then(() => {
        this.msgSuccess("删除成功");
        this.getList();
      }).catch(function () {
      });
    }
    ,
    handleAddOrUpdate() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let temp = Object.assign({}, this.formData);
          let param = Object.assign(temp, {
            startTime: this.formData.startTime[0],
            endTime: this.formData.startTime[1]
          });
          couponApi.updateOrSave({
            ...temp
          }).then((res) => {
            this.initParamData();
            this.open = false;
            this.getList();
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
    ,
    openUpdateDialog(row) {
      this.title = '修改';
      this.open = true;
      this.formData = Object.assign({}, row);
      Object.assign(this.formData, {
        couponType: this.formData.couponType + "",
        startTime: [this.formData.startTime, this.formData.endTime]
      })
    }
    ,
    openAddDialog() {
      this.title = '添加';
      this.open = true;
      this.initParamData()
    }
    ,
    initParamData() {
      this.formData = {
        couponType: '1'
      }
    }
  }
}
;
</script>
<style lang="scss" scoped>

</style>
